package com.jack.cms.ueditor.upload;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.jack.cms.core.util.SpringContextHolder;
import com.jack.cms.oss.core.QiniuImageUtils;
import com.jack.cms.oss.service.FileService;
import com.jack.cms.oss.service.ImageService;
import com.jack.cms.oss.service.OssService;
import com.jack.cms.ueditor.define.AppInfo;
import com.jack.cms.ueditor.define.BaseState;
import com.jack.cms.ueditor.define.FileType;
import com.jack.cms.ueditor.define.State;
import com.jack.cms.ueditor.define.UploadType;

public class BinaryQiniuUpload {

	private static void uplodaTypeProcess(MultipartFile myfile, Map<String, Object> conf) throws IOException {
		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if (myfile.getBytes() != null && myfile.getBytes().length > maxSize) {
			throw new RuntimeException(String.format("图片上传大小控制在%sM以内，请重新上传", maxSize/1024/1024));
		}
		if (UploadType.MEDIA.equals(conf.get("type"))) {
			if (StringUtils.isNotBlank(myfile.getOriginalFilename())
					&& !QiniuImageUtils.checkImageSuffix(myfile.getOriginalFilename())) {
				throw new RuntimeException("系统只支持.jpg,.jpeg,.gif,.png,.bmp格式的图片，请重新上传");
			}
		}
	}

	private static OssService getOssService(Map<String, Object> conf) {
		if (UploadType.MEDIA.equals(conf.get("type"))) {
			return SpringContextHolder.getBean(ImageService.class);
		} else {
			return SpringContextHolder.getBean(FileService.class);
		}
	}

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		Map<String, MultipartFile> files = ((MultipartRequest) request).getFileMap();
		if (files != null) {
			Iterator<MultipartFile> iterator = files.values().iterator();
			OssService service = getOssService(conf);
			while (iterator.hasNext()) {
				try {
					MultipartFile myfile = (MultipartFile) iterator.next();

					uplodaTypeProcess(myfile, conf);

					String srcFileName = myfile.getOriginalFilename();
					String suffix = FileType.getSuffixByFilename(srcFileName);
					String ossFileName = service.save(myfile);
					String url = service.getUrl(ossFileName);
					State state = new BaseState(true);
					state.putInfo("size", -1);
					state.putInfo("title", ossFileName);
					state.putInfo("url", url);
					state.putInfo("type", suffix);
					state.putInfo("original", srcFileName);
					return state;
				} catch (FileUploadException e) {
					return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
				} catch (Exception e) {
					return new BaseState(false, e.getMessage());
				}
			}
		}
		return new BaseState(false, "上传文件为空！");
	}
}
